import ma.const
import ma.utils.location

import os
import os.path
import getopt
import sys


hadoop_exec = ma.const.XmlData.get_filepath_str_data(ma.const.xml_hadoop_exec)
conf_dir = ma.utils.location.get_ma_conf_path()
std_mf_filename = ma.const.XmlData.get_str_data(ma.const.xml_map_flags_filename)
std_rf_filename = ma.const.XmlData.get_str_data(ma.const.xml_reduce_flags_filename)
std_jc_filename = 'testjobconf.xml'
mf_filename = ma.const.XmlData.get_str_data(ma.const.xml_map_flags_filename)
rf_filename = ma.const.XmlData.get_str_data(ma.const.xml_reduce_flags_filename)
jc_filename = ma.const.XmlData.get_str_data(ma.const.xml_job_conf_filename)

cpystd = False
cpyjc = False
optlist, args = getopt.getopt(sys.argv[1:], 'cj')
if len(args) != 1:
    print('usage: python refreshflags.py [-c for copy standard flags] [-j if jobconf.xml needs to be copied] [job_id]')
    sys.exit(-1)
else:
    if len(optlist) > 0:
        for opt in optlist:
            if opt[0] == '-c':
                cpystd = True
            elif opt[0] == '-j':
                cpyjc = True

# get argument variables    
job_id = int(args[0])

if cpystd:
    print("Copying Flags")
    os.system('cp ' + os.path.join(conf_dir, std_mf_filename) + ' ' + mf_filename)
    os.system('cp ' + os.path.join(conf_dir, std_rf_filename) + ' ' + rf_filename)
    if cpyjc:
        os.system('cp ' + os.path.join(conf_dir, std_jc_filename) + ' ' + jc_filename)

print("Removing old flags from DFS")
os.system(hadoop_exec + ' fs -rm ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_map_flags, job_id))
os.system(hadoop_exec + ' fs -rm ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_reduce_flags, job_id))
if cpyjc:
    os.system(hadoop_exec + ' fs -rm ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_conf, job_id))
print("Copying fresh flags")
os.system(hadoop_exec + ' fs -copyFromLocal ' + mf_filename + ' ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_map_flags, job_id))
os.system(hadoop_exec + ' fs -copyFromLocal ' + rf_filename + ' ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_reduce_flags, job_id))
if cpyjc:
    os.system(hadoop_exec + ' fs -copyFromLocal ' + jc_filename + ' ' + ma.const.JobsXmlData.get_dfs_filepath_str_data(ma.const.xml_dfs_path_job_conf, job_id))

print("Done - Khuda-Hafiz!")
